package com.guw.TestThread;

import java.util.concurrent.locks.ReentrantLock;

//JUC包下的:java.util.concurrent.locks.Lock接口:通过显式定义同步锁对象来实现同步;
//是控制多个线程对共享资源进行访问的工具
//锁提供了对共享资源的独占访问,每次只能有一个线程对Lock对象加锁,线程开始访问共享资源前应先获得Lock对象
//可重入锁ReentrantLock类实现了Lock,拥有与synchorized相同的并发性和内存语义;
public class TestLock {
    public static void main(String[] args) {
        TestLock2 testLock2 = new TestLock2();
        new Thread(testLock2, "A").start();
        new Thread(testLock2, "B").start();
        new Thread(testLock2, "C").start();
    }
}

class TestLock2 implements Runnable {
    int tickets = 5;

    //定义Lock
    private ReentrantLock reentrantLock = new ReentrantLock();

    //记住这个格式,如果不在合适的地方加锁,最后还是可能出错
    @Override
    public void run() {
        while (true) {
            try {
                reentrantLock.lock();
                if (tickets > 0) {
                    try {
                        Thread.sleep(10);
                        System.out.println(Thread.currentThread().getName() + "----->" + tickets--);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else break;
            } finally {
                reentrantLock.unlock();
            }
        }
    }
}
